from backend.utils.db import get_db_connection


class SynonymEngine:
    def __init__(self):
        self.synonym_map = {}
        self.load_synonyms()

    def load_synonyms(self):
        """从数据库加载同义词映射"""
        # 添加额外同义词
        extra_synonyms = {
            "价格": ["多少钱", "售价", "价位", "报价", "什么价", "优惠价", "价"],
            "订单": ["单号", "物流", "快递", "发货", "配送"],
            "退货": ["退掉", "退款", "退钱", "返还"],
            "换货": ["更换", "调换", "换新"],
            "修改": ["更改", "更新", "调整", "变更"],
            "成分": ["配料", "配方", "材料", "构成"]
        }
        for keyword, synonyms in extra_synonyms.items():
            if keyword not in self.synonym_map:
                self.synonym_map[keyword] = []
            for synonym in synonyms:
                if synonym not in self.synonym_map[keyword]:
                    self.synonym_map[keyword].append(synonym)

    def replace_synonyms(self, text):
        """替换文本中的同义词"""
        for keyword, synonyms in self.synonym_map.items():
            for synonym in synonyms:
                text = text.replace(synonym, keyword)
        return text